package r

import (
	"encoding/json"
	"fmt"

	"gopkg.in/resty.v1"
)

type rc struct {
	Schema   string
	Endpoint string
}

type CommonResp struct {
	Code    int         `json:"code"`
	Message string      `json:"msg"`
	Data    interface{} `json:"data"`
}

type CommonError struct {
	Code     int    `json:"code"`
	Message  string `json:"msg"`
	GMessage string `json:"message"`
}

type R interface {
	Post(apiPoint string, head *map[string]string, body interface{}, result interface{}) error
}

func NewRc(schema, endpoint string) R {
	return &rc{
		Schema:   schema,
		Endpoint: endpoint,
	}
}

func (r *rc) Post(apiPoint string, head *map[string]string, body interface{}, result interface{}) error {
	commonResp := CommonResp{
		Data: result,
	}
	commonError := CommonError{}

	realPoint := apiPoint
	if apiPoint[:1] != "/" {
		realPoint = "/api/" + apiPoint
	}
	req := resty.R().SetHeader("Content-Type", "application/json")
	if head != nil {
		for k, v := range *head {
			req.SetHeader(k, v)
		}
	}
	if body != nil {
		req.SetBody(body)
	}
	req.SetResult(&commonResp)
	resp, err := req.Post(fmt.Sprintf("%s://%s%s", r.Schema, r.Endpoint, realPoint))
	if err != nil {
		return err
	}
	if resp.RawResponse.StatusCode != 200 {
		json.Unmarshal(resp.Body(), &commonError)
		if commonError.GMessage != "" {
			return fmt.Errorf("%d: %s", resp.RawResponse.StatusCode, commonError.GMessage)
		}
		return fmt.Errorf("%d: %s", commonError.Code, commonError.Message)
	}
	// fmt.Printf("%v\n", resp)
	return nil
}
